define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'newhouse/building/items/index' + location.search,
                    add_url: 'newhouse/building/items/add',
                    edit_url: 'newhouse/building/items/edit',
                    view_url: 'newhouse/building/items/view',
                    del_url: 'newhouse/building/items/del',
                    multi_url: 'newhouse/building/items/multi',
                    table: 'newhouse_building_items',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
            url: $.fn.bootstrapTable.defaults.extend.index_url,
            pk: 'id',
            sortName: 'id',
            columns: [
                [
                    {checkbox: true},
                    {field: 'id', title: __('Id')},
                    {field: 'building_name', title: __('Building_name')},
                    {field: 'is_top', title: '是否置顶'},
                    {field: 'average_price', title: __('Average_price'), operate:'BETWEEN',visible:false },
                    {field: 'validate_begin', title: __('Validate_begin'), operate:'RANGE', addclass:'datetimerange'},
                    {field: 'validate_end', title: __('Validate_end'), operate:'RANGE', addclass:'datetimerange'},
                    {field: 'address', title: __('Address'),visible:false},
                    {field: 'last_sell', title: __('Last_sell'), operate:'RANGE', addclass:'datetimerange'},
                    {field: 'get_date', title: __('Get_date'), operate:'RANGE', addclass:'datetimerange',visible:false},
                    {field: 'property_year', title: __('Property_year')},
                    {field: 'volume_ratio', title: __('Volume_ratio'), operate:'BETWEEN'},
                    {field: 'property_fee', title: __('Property_fee')},
                    {field: 'greening_rate', title: __('Greening_rate'), operate:'BETWEEN'},
                    {field: 'parking_spaces', title: __('Parking_spaces')},
                    {field: 'house_quantity', title: __('House_quantity')},
                    {field: 'developer', title: __('Developer'),visible:false},
                    {field: 'property_company', title: __('Property_company'),visible:false},
                    {field: 'scene_person', title: __('Scene_person'),visible:false},
                    {field: 'scene_person_tel', title: __('Scene_person_tel'),visible:false},
                    {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate,
                        buttons:[
                            {
                                name:'view',
                                text:'查看',
                                title:'查看',
                                icon:'fa fa-building',
                                classname:'btn btn-xs btn-success btn-view btn-dialog',
                                url:'newhouse/building/items/view'
                            }
                        ],formatter: Table.api.formatter.operate
                    }
                ]
                ]
            });
        
            // 为表格绑定事件
            Table.api.bindevent(table);

            table.on('post-body.bs.table',function(){
                $("a.btn-view").data('area',["95%","95%"]);
                $("a.btn-editone").data('area',["95%","95%"]);
            });
        },
        add: function () {
            this.position(31.866842,117.282699);
            Controller.api.bindevent();
        },
        edit: function () {
            this.position(form_lat,form_lng);

            var btn = '<button class="btn btn-success btn-setpicture btn-xs" data-picture-id="" style="position:absolute;top:38px;right:15px;display:none">设为封面</button>';
           
                // //图片裁剪
                $(document).on('click', '.btn-setpicture', function () {
                    var url = $(this).prev().prev().attr("data-url");
                    $.get('newhouse/building/items/changePicture',{id:building_id,picture_path:url},function(ret){
                        if(ret.code){
                            $("#p-picture").find("a").attr("href",url);
                            $("#p-picture").find("a").attr("data-url",url);
                            $("#p-picture").find("img").attr("src",url+"?a=" + (new Date()).getTime());
                            $("#c-picture").val(url);
                        }
                    });
                    return false;
                });
        
                // var insertBtn = function () {
                //     return arguments[0].replace(arguments[2], btn + arguments[2]);
                // };
                setTimeout(function(){
                    $(".setpicture li").each(function () {
                        var $t=$(this);
                        $btn=$(btn);
                       
                        $t.append($btn);
                        $btn.attr("data-picture-id",$t.attr("data-picture-id"));
                        $t.mouseover(function(){
                            $(".btn-setpicture").css("display","none");
                            $(this).find(".btn-setpicture").css("display","block");
                        }).mouseout(function(){
                            $(this).find(".btn-setpicture").css("display","none");
                        });
                    });

                },2000);
            //
            Controller.api.bindevent();
        },
        view:function(){
            this.position(form_lat,form_lng);
            renderFollow();
         
            function renderFollow(){
                // 加载跟进
                Fast.api.ajax({
                    'url':'newhouse/building/follow',
                    data:{building_id:building_id},
                    method:'get'
                },function(data,ret){
                    var value=ret.rows;
                    $("#ulFollow").empty();
                    for(var i=0;i<value.length;i++){
                        var tmp=value[i];
                        var str='<li>[' + tmp.create_time_text + ']';
                        str +='[ '+ tmp.state + ' ]';
                        str += tmp.comment;
                        str += ' [ ' + tmp.admin.username + ' ] ';
                        str+='</li>';
                        $("#ulFollow").append(str);
                    }
                    $("#tdBuildingState").text(ret.building_state);
                    
                    return false;
                },function(data,ret){
                    return false;
                });
            }
            $("#btnNewFollow").click(function(){
                Fast.api.open("newhouse/building/follow/add?building_id=" + building_id, '新增跟进', {
                    callback: function (data) {
                        renderFollow();
                    }
                });
                return false;
            });
    


            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        },
        position: function(lat,lng){
            //地图
            var map = new BMap.Map("cop-map-container");
            //
            map.addControl(new BMap.NavigationControl());    
            map.addControl(new BMap.ScaleControl());    
            map.addControl(new BMap.OverviewMapControl());    
            map.addControl(new BMap.MapTypeControl());    
            map.setCurrentCity("合肥"); // 仅当设置城市信息时，MapTypeControl的切换功能才能可用  

            // 创建地图实例  
            var point = new BMap.Point(lng,lat);
            // 创建点坐标  
            map.centerAndZoom(point, 16);
            // 初始化地图，设置中心点坐标和地图级别  
            var marker = new BMap.Marker(point);        // 创建标注    
            map.addOverlay(marker);                     // 将标注添加到地图中 
            marker.enableDragging();    
            marker.addEventListener("dragend", function(e){    
                $("input#c-lng").val(e.point.lng);
                $("input#c-lat").val(e.point.lat);
            });
            
            $("a.link-map").click(function(){
                if(!$("input#c-building_name").val())return;
                var myGeo = new BMap.Geocoder();
                // 将地址解析结果显示在地图上，并调整地图视野    
                myGeo.getPoint($("input#c-building_name").val(), function(point){      
                    if (point) {      
                        map.centerAndZoom(point, 16);      
                        marker.setPosition(point);
                    //	map.addOverlay(new BMap.Marker(point));
                        $("input#c-lng").val(point.lng);
                        $("input#c-lat").val(point.lat);
                        myGeo.getLocation(point, function(result){      
                            if (result){      
                                $("input#c-address").val(result.address);
                            }      
                        });
                    }      
                }, 
                "合肥市");

            });
        }
    };
    return Controller;
});